import { message } from '@/components/Message'
import router from '@/router'
import store from '@/store'
import axios from 'axios'

// baseURL设置 、超时时间设置
const instance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 5000
})

// 请求拦截器
instance.interceptors.request.use((config) => {
  // 1、获取token
  const { token } = store.state.user.profile
  // 2、请求头设置 token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, err => Promise.reject(err))

// 响应拦截器
instance.interceptors.response.use(response => {
  return response.data
}, err => {
  console.dir(err)
  message({ type: 'error', text: err.response.data.message })
  // 响应错误，用户 token校验失败 401
  if (err.response && err.response.status === 401) {
    // encodeURIComponent 把 URL 进行特殊字符安全转码
    const redirectUrl = encodeURIComponent(router.currentRoute.value.fullPath)
    // 跳转到登录页并记录回跳地址
    router.push('/login?redirectUrl=' + redirectUrl)
  }
  return Promise.reject(err)
})
// [method.toLowerCase() === 'get' ? 'params' : 'data']  自动设置 key值
const request = (url, method = 'get', submitData) => instance({ url, method, [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData })
export default request
